package com.sto.stoapp.activity.aviation;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.StoLoginActivity;
import com.sto.stoapp.activity.administrator.StoAdminMainActivity;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.broadcast.LogoutBroad;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.http.BaseMessage;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.manager.AccessControlManager;
import com.sto.stoapp.manager.AlarmClockManager;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.service.TimingService;
import com.sto.stoapp.upload.UploadDataService;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseActivity;
import com.sto.stoapp.widget.BaseDialog;

import java.util.List;

import sto.android.app.StoPdaKeyEvent;

/**
 * 角色选择，管理员，扫描员，提货员
 */
public class StoAviationSelectActivity extends BaseActivity {

	public static final String IS_LOCAL_LOGIN = "is_local_login";

	private TextView textTitle;
	private Button aviScannerBtn, aviPickUpBtn, adminBtn;
	private boolean isOffline;
	private LogoutBroad logoutBroad;
	private List<String> menus = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sto_aviation_select);
		Intent intent = getIntent();
		isOffline = intent.getBooleanExtra(IS_LOCAL_LOGIN, false);
		// menus = intent.getStringArrayListExtra(BaseMessage.ROLE_MENU);

		menus = AccessControlManager.getInstance(this).getListMenus(
				StoFilePreference.getInstance(this).getRoleMenu());

		register(HomeBroadAction.AVIATION_BROAD);
		initWidget();
		initListener();
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		keyCode= StoApplication.getStoJni().getEventFuction(keyCode);
		switch (keyCode) {
		case StoPdaKeyEvent.KEYCODE_0:
			if (adminBtn.getVisibility() != View.GONE) {
				gotoAdminView();
			}
			break;
		case StoPdaKeyEvent.KEYCODE_1:
			if (aviScannerBtn.getVisibility() != View.GONE) {
				gotoScannerView();
			}
			break;
		case StoPdaKeyEvent.KEYCODE_2:
			if (aviPickUpBtn.getVisibility() != View.GONE) {
				gotoPickUpView();
			}
			break;
		case StoPdaKeyEvent.KEYCODE_DEL:
			// onBackPressed();
			break;
		default:
			break;
		}
		return super.onKeyUp(keyCode, event);
	}

	private void gotoAdminView() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, StoAdminMainActivity.class);
		startActivity(intent);
		finish();
	}

	private void initWidget() {
		textTitle = (TextView) findViewById(R.id.avi_title);
		aviScannerBtn = (Button) findViewById(R.id.avi_scanner);
		aviPickUpBtn = (Button) findViewById(R.id.avi_pick_up);
		adminBtn = (Button) findViewById(R.id.avi_admin);
		adminBtn.setVisibility(View.GONE);
		aviScannerBtn.setVisibility(View.GONE);
		aviPickUpBtn.setVisibility(View.GONE);
		setStoTitle();
		initButton();
	}

	private void initButton() {
		if (menus != null) {

			for (int i = 1; i < menus.size(); i++) {
				if (AccessControlManager.ALL.equals(menus.get(i))) {
					// 增加管理员
					adminBtn.setVisibility(View.VISIBLE);
					aviScannerBtn.setVisibility(View.VISIBLE);
					aviPickUpBtn.setVisibility(View.VISIBLE);
					return;
				} else if (AccessControlManager.FULL_BUSI.equals(menus.get(i))) {
					// 默认全业务
					// adminBtn.setVisibility(View.VISIBLE);
					aviScannerBtn.setVisibility(View.VISIBLE);
					aviPickUpBtn.setVisibility(View.VISIBLE);
					return;
				} else if (AccessControlManager.ADMINTER.equals(menus.get(i))) {
					// 增加管理员
					adminBtn.setVisibility(View.VISIBLE);
				} else if (AccessControlManager.SCANNER.equals(menus.get(i))) {
					// 增加扫描员
					aviScannerBtn.setVisibility(View.VISIBLE);
				} else if (AccessControlManager.PICKUP.equals(menus.get(i))) {
					// 增加提货员
					aviPickUpBtn.setVisibility(View.VISIBLE);
				}
			}
		}
	}

	@Override
	public void onBackPressed() {

		final BaseDialog dialog = new BaseDialog(this);
		dialog.setTitles(this.getText(R.string.change_user).toString());
		dialog.show();
		dialog.getvMessage().setVisibility(View.GONE);
		dialog.getvPresentation().setVisibility(View.GONE);
		dialog.setOnBackClickListener(new OnBackClickListener() {

			@Override
			public void onBackClickListener(boolean res) {
				dialog.dismiss();
				if (res) {
					// 恢复时间同步和订单状态
					Intent intent = new Intent(StoAviationSelectActivity.this,
							StoLoginActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					stopStoServiece();
					finish();
				}
			}
		});

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		// 退出
		if (intent.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE) != null) {
			if (intent.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE)
					.equals(HomeBroadAction.ALARM_LOGOUT)) {
				Intent logoutIntent = new Intent(this, StoLoginActivity.class);
				startActivity(logoutIntent);
				stopStoServiece();
				finish();
			}
		}
	}

	/**
	 * 注册广播
	 * 
	 * @param action
	 *            事件
	 */
	public void register(String action) {
		IntentFilter filter = new IntentFilter(action);
		logoutBroad = new LogoutBroad();
		registerReceiver(logoutBroad, filter);
	}

	/**
	 * 注销广播
	 */
	private void unRegister() {
		if (logoutBroad != null) {
			unregisterReceiver(logoutBroad);
		}
	}

	@Override
	protected void onDestroy() {
		// stopStoServiece();
		unRegister();
		super.onDestroy();
	}

	/**
	 * 切换用户时，停止后台服务
	 */
	private void stopStoServiece() {
		// 退出的时候关闭后台服务
		StoFilePreference.getInstance(StoAviationSelectActivity.this)
				.clearTimeSynData();
		stopService(new Intent(this, StoDownServer.class));
		stopService(new Intent(this, UploadDataService.class));
		stopService(new Intent(this, TimingService.class));
	}

	/***
	 * 显示标题
	 */
	private void setStoTitle() {
		try {
			StringBuffer sb = new StringBuffer();
			sb.append(textTitle.getText()).append("(")
					.append(StoFilePreference.getInstance(this).getUserName())
					.append(")");
			textTitle.setText(sb);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initListener() {
		// 管理员
		adminBtn.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {
				gotoAdminView();
			}
		});
		// 扫描员
		aviScannerBtn.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {
				gotoScannerView();
			}
		});
		// 提货员
		aviPickUpBtn.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {
				gotoPickUpView();
			}
		});
	}

	/**
	 * 跳转到扫描员界面
	 */
	private void gotoScannerView() {
		UnifiedStaticType.loginType = BaseMessage.AVIATION_A_VERSION;
		startAviationScanDown(isOffline);
		Intent intent = new Intent(this, StoAviationScannerMainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		// AlarmClockManager.getInstance(this).startAlarm(
		// HomeBroadAction.	AVIATION_SCANNER_BROAD,
		// HomeBroadAction.ALARM_LOGOUT);
		finish();
	}

	/**
	 * 跳转到提货员界面
	 */
	private void gotoPickUpView() {
		UnifiedStaticType.loginType = BaseMessage.AVIATION_T_VERSION;
		startAviationPickerDown(isOffline);
		Intent intent = new Intent(this, StoAviationPickUpMainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		// AlarmClockManager.getInstance(this).startAlarm(
		// HomeBroadAction.PICKER_BROAD,
		// HomeBroadAction.ALARM_LOGOUT);
		finish();
	}

	private void startAviationScanDown(boolean isOffline) {
		Intent downIntent = new Intent(this, StoDownServer.class);
		if (!isOffline) {
			downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
					new int[] { MessageType.SYNCH_TIME_TYPE });
		} else {
			downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
					new int[] { MessageType.SYNCH_TIME_TYPE });
		}
		startService(downIntent);
	}

	private void startAviationPickerDown(boolean isOffline) {
		// Intent downIntent = new Intent(this, StoDownServer.class);
		Intent downIntent = new Intent(StoDownServer.UPDATE_ACTION);
		if (!isOffline) {

			downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
					new int[] { MessageType.SYNCH_TIME_TYPE });
			sendBroadcast(downIntent);

		} else {
			downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
					new int[] { MessageType.SYNCH_TIME_TYPE });
		}
		startService(downIntent);
	}

}
